package com.itfreer.gis.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.gis.entity.GisBookEntity;
import com.itfreer.utils.json.JsonUtils;
import com.itfreer.utils.sys.SystemParameter;

/**
 * 定义书签功能接口
 */
@Component
@Path("/cgisbook/")
public class CurrentGisBookService {

	@Autowired
	private GisBookService gisBookService;

	@Autowired(required = false)
	private SystemParameter systemParameter;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@POST
	@Path("/getEntitys")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public List<GisBookEntity> getEntitys(String data,
			@Context HttpServletRequest request) throws IOException {
		HashMap<String, Object> args = this.getRestParam(data);
		String queryFields = null;
		String whereString = null;
		String orderString = null;
		Integer pageSize = 10;
		Integer pageIndex = 1;

		if (args != null) {
			if (args.containsKey("queryFields") && args.get("queryFields") != null)
				queryFields = args.get("queryFields").toString();
			if (args.containsKey("where") && args.get("where") != null)
				whereString = args.get("where").toString();
			if (args.containsKey("order") && args.get("order") != null)
				orderString = args.get("order").toString();
			if (args.containsKey("pageSize") && args.get("pageSize") != null)
				pageSize = new Integer(args.get("pageSize").toString());
			if (args.containsKey("pageIndex") && args.get("pageIndex") != null)
				pageIndex = new Integer(args.get("pageIndex").toString());
		}
		HashMap where = JsonUtils.toBean(whereString, HashMap.class);
		HashMap order = JsonUtils.toBean(orderString, HashMap.class);

		final HttpSession httpSession = request != null ? request.getSession(false) : null;
		Object userId = httpSession != null ? httpSession.getAttribute("user_id") : null;

		if (systemParameter != null && userId != null) {
			HashMap<String, Object> curWhere = new HashMap<String, Object>();
			curWhere.put("registerService", systemParameter.getsId());
			curWhere.put("userid", userId);
			where = curWhere;
		}

		return gisBookService.getEntitys(queryFields, where, order, pageSize, pageIndex);
	}
	
	/**
	 * 解决请求参数问题
	 * 
	 * @param data
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private HashMap<String, Object> getRestParam(String data) {
		HashMap<String, Object> args = null;
		if (data == null || "".equals(data.trim()))
			return args;
		// 解决不同浏览器返回传递参数不一致问题-s-
		try {
			args = JsonUtils.toBean(data, HashMap.class);

		} catch (Exception e) {
			try {
				String ENCODE = "UTF-8";
				data = java.net.URLDecoder.decode(data, ENCODE);
				if (data != null && !"".equals(data.trim())) {
					String[] lst = data.split("&");
					args = new HashMap<String, Object>();
					for (String item : lst) {
						if (item == null || "".equals(item.trim()))
							continue;
						String[] ivalue = item.split("=");
						if (ivalue != null) {
							if (ivalue.length > 1) {
								args.put(ivalue[0], ivalue[1]);
							} else {
								args.put(ivalue[0], null);
							}
						}

					}
				}
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		return args;
		// 解决不同浏览器返回传递参数不一致问题-e-
	}

	/**
	 * 获取当前条件下的数据行总数
	 * 
	 * @param where
	 *            查询条件
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@POST
	@Path("/getRowCounts")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public Long getRowCounts(String data, @Context HttpServletRequest request) throws IOException {
		HashMap<String, Object> args = this.getRestParam(data);
		String whereString = null;
		if (args != null) {
			if (args.containsKey("where") && args.get("where") != null)
				whereString = args.get("where").toString();
		}
		HashMap where = JsonUtils.toBean(whereString, HashMap.class);
		
		final HttpSession httpSession = request != null ? request.getSession(false) : null;
		Object userId = httpSession != null ? httpSession.getAttribute("user_id") : null;

		if (systemParameter != null && userId != null) {
			HashMap<String, Object> curWhere = new HashMap<String, Object>();
			curWhere.put("registerService", systemParameter.getsId());
			curWhere.put("userid", userId);
			where = curWhere;
		}
		
		return gisBookService.getRowCounts(where);
	}

	/**
	 * 获取实体
	 * 
	 * @param guid
	 *            唯一值
	 * @return
	 */
	@POST
	@Path("/getEntity/{id:.+}")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public GisBookEntity getEntity(@PathParam("id") String guid) {
		return gisBookService.getEntity(guid);
	}

	/**
	 * 添加实体
	 * 
	 * @param entity
	 *            添加实体
	 * @return
	 * @throws IOException
	 */
	@POST
	@Path("/add")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public GisBookEntity add(String data, @Context HttpServletRequest request) throws IOException {
		HashMap<String, Object> args = this.getRestParam(data);
		String entityJson = null;
		if (args != null && args.containsKey("entity") && args.get("entity") != null) {
			entityJson = args.get("entity").toString();
		}
		GisBookEntity entity = (GisBookEntity) JsonUtils.toBean(entityJson, GisBookEntity.class);
		
		final HttpSession httpSession = request != null ? request.getSession(false) : null;
		Object userId = httpSession != null ? httpSession.getAttribute("user_id") : null;

		if (systemParameter != null && userId != null) {
			entity.setRegisterService(systemParameter.getsId());
			entity.setUserid(userId.toString());
		}
		
		return gisBookService.add(entity);
	}

	/**
	 * 更新实体
	 * 
	 * @param entity
	 *            实体
	 * @return
	 * @throws IOException
	 */
	@POST
	@Path("/update")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public GisBookEntity update(String data, @Context HttpServletRequest request) throws IOException {
		HashMap<String, Object> args = this.getRestParam(data);
		String entityJson = null;
		if (args != null && args.containsKey("entity") && args.get("entity") != null) {
			entityJson = args.get("entity").toString();
		}
		GisBookEntity entity = (GisBookEntity) JsonUtils.toBean(entityJson, GisBookEntity.class);
		
		final HttpSession httpSession = request != null ? request.getSession(false) : null;
		Object userId = httpSession != null ? httpSession.getAttribute("user_id") : null;

		if (systemParameter != null && userId != null) {
			entity.setRegisterService(systemParameter.getsId());
			entity.setUserid(userId.toString());
		}
		
		return gisBookService.update(entity);
	}

	/**
	 * 删除实体
	 * 
	 * @param guid
	 *            唯一值
	 */
	@DELETE
	@Path("/delete/{id:.+}")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public void delete(@PathParam("id") String guid) {
		gisBookService.delete(guid);
	}

	/**
	 * 指量删除实体
	 * 
	 * @param guid
	 *            唯一值集
	 */
	@DELETE
	@Path("/deletes/{ids:.+}")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public void deletes(@PathParam("ids") String guids) {
		gisBookService.deletes(guids);
	}
}
